<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <input type="text" class="username" placeholder="用户名" value="zhangsan123">
    <input type="password" class="password" placeholder="密码" value="123456">
    <button type="button" onclick="doLogin()">登陆</button>
    <br>
    <input id="text" type="text" />
    <button onclick="send()">发送消息</button>
    <hr />
    <button onclick="closeWebSocket()">关闭WebSocket连接</button>
    <hr />
    <div id="message"></div>

    <script src="https://s0.pstatp.com/cdn/expire-1-M/jquery/3.4.0/jquery.min.js"></script>
    <script>
        var websocket = null;
        const host = 'bufantec.com';
        var loginUrl = `http://${host}/api/test/user/doLogin`;
        var userInfoUrl = `http://${host}/api/test/user/detail`
        var userInfo = {};
        function doLogin() {

            $.ajax({
                url: loginUrl,
                method: 'post',
                data: {
                    username: $('.username').val(),
                    password: $('.password').val()
                },
                success(res) {
                    console.log(res);
                    if (res.code == 'success') {
                        $.ajax({
                            url: userInfoUrl,
                            data: {
                                id: res.userId
                            },
                            success(res) {
                                window.userInfo = res.data
                                console.log('登陆成功,开启websocket...');
                                window.initWebsocket(window.userInfo.userId);
                            }
                        })
                    }
                }
            })
        }

        function initWebsocket(userId) {

            //判断当前浏览器是否支持WebSocket
            if ('WebSocket' in window) {
                websocket = new WebSocket(`ws://${host}/websocket.ws/` + userId);
            }
            else {
                alert('当前浏览器 Not support websocket')
            }

            //连接发生错误的回调方法
            websocket.onerror = function (err) {
                console.log('err', err)
                setMessageInnerHTML("WebSocket连接发生错误");
            };

            //连接成功建立的回调方法
            websocket.onopen = function () {
                setMessageInnerHTML("WebSocket连接成功");
            }

            //接收到消息的回调方法
            websocket.onmessage = function (event) {
                console.log(event);
                var msg =  JSON.parse(event.data);
                var msgStr = msg.from.nickname+': '+msg.msg;
                setMessageInnerHTML(msgStr);
            }

            //连接关闭的回调方法
            websocket.onclose = function () {
                setMessageInnerHTML("WebSocket连接关闭");
            }

            //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
            window.onbeforeunload = function () {
                closeWebSocket();
            }
        }
        //将消息显示在网页上
        function setMessageInnerHTML(innerHTML) {
            document.getElementById('message').innerHTML += innerHTML + '<br/>';
        }
        //关闭WebSocket连接
        function closeWebSocket() {
            websocket.close();
        }
        //发送消息
        function send() {
            if(!window.userInfo||!websocket) {
                alert('请先登陆!');
                return;
            }
            var msg = document.getElementById('text').value;
            var msgObj = {
                userId: window.userInfo.userId,
                msg
            }
            websocket.send(JSON.stringify(msgObj));
        }
    </script>
</body>

</html>